package finanz.kontrolle;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import classes.Funcoes;
import classes.Parametros;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class BancoCadastroActivity extends MenuActivity implements OnClickListener {
	
	private Parametros par = Parametros.getInstance();
	private String id;
	private EditText txtNome;
	private EditText txtDescricao;
	
	public void onCreate( Bundle bundle ) {
		super.onCreate( bundle );
		setContentView( R.layout.bancocadastro );
		
		Bundle extras = getIntent().getExtras();

		id = extras.getString( "BancoID" );
		
		txtNome = ( EditText ) findViewById( R.id.txtNomeBanco );
		txtDescricao = ( EditText ) findViewById( R.id.txtDescricaoBanco );
		
		if ( !id.equals( "0" ) ) {
			this.preencherText();
		}
		
		Button btnSalvar = ( Button ) findViewById( R.id.btnSalvar );
		btnSalvar.setOnClickListener( this );
		
		Button btnCancelar = ( Button ) findViewById( R.id.btnCancelar );
		btnCancelar.setOnClickListener( this );
	}

	public void onClick( View arg0 ) {
		int mensagem = R.string.msgSalvoSucesso;
		
		switch ( arg0.getId()  ) {
			case R.id.btnSalvar:
						if ( txtNome.getText().length() <= 0 )
							 mensagem =  R.string.msgPreenchaNome;
						else
							mensagem = this.salvar();
					
						if ( mensagem != R.string.msgSalvoSucesso ) {
							new AlertDialog.Builder( this )
							.setTitle( "Alerta" )
							.setMessage( mensagem )
							.setNeutralButton( "Ok", null).show();
						}
				break;
			case R.id.btnCancelar:
					this.volta();
				break;
		}
	}
	
	private void volta() {
		Intent i = new Intent( BancoCadastroActivity.this, BancoActivity.class );
		startActivity( i );
		finish();
	}
	
	private void preencherText() {
		String strUrl = par.getUrl().toString() + getResources().getString( R.string.urlBancoEditar);
		
		HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost( strUrl );
	    
	    try {
	        List<NameValuePair> BancoValuePairs = new ArrayList<NameValuePair>(2);
	        BancoValuePairs.add(new BasicNameValuePair("DatabaseID", par.getDatabase()));
	        BancoValuePairs.add(new BasicNameValuePair("BancoID", id));
	        httppost.setEntity(new UrlEncodedFormEntity(BancoValuePairs));

	        HttpResponse response = httpclient.execute(httppost);

	        Funcoes f = new Funcoes();
	        StringBuilder retorno = f.inputStreamToString( response.getEntity().getContent() );

	        try {
				
	        	txtNome = ( EditText ) findViewById( R.id.txtNomeBanco );
				txtDescricao = ( EditText ) findViewById( R.id.txtDescricaoBanco );
	        	
				JSONObject jo = new JSONObject( retorno.toString() );
				
				txtNome.setText( jo.getString( "Nome" ) );
				txtDescricao.setText( jo.getString( "Descricao" ) );
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
	        
	    } catch (IOException e) {
	    	e.printStackTrace();
	    }
	}
	
	protected int salvar() {
		int mensagem = R.string.msgSalvoSucesso;
		
		String strUrl = par.getUrl().toString() + getResources().getString( R.string.urlBancoSalvar );
		
		HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost( strUrl );

	    try {
	        List<NameValuePair> BancoValuePairs = new ArrayList<NameValuePair>(4);
	        BancoValuePairs.add(new BasicNameValuePair("DatabaseID", par.getDatabase()));
	        BancoValuePairs.add(new BasicNameValuePair("BancoID", id));
	        BancoValuePairs.add(new BasicNameValuePair("Nome", txtNome.getText().toString()));
	        BancoValuePairs.add(new BasicNameValuePair("Descricao", txtDescricao.getText().toString()));
	        httppost.setEntity(new UrlEncodedFormEntity(BancoValuePairs));

	        HttpResponse response = httpclient.execute(httppost);

	        Funcoes f = new Funcoes();
	        StringBuilder retorno = f.inputStreamToString( response.getEntity().getContent() );

	        if ( retorno.toString().equals( "1" ) ) {
				mensagem = R.string.msgSalvoSucesso;
				
				Toast t = Toast.makeText( this, mensagem, Toast.LENGTH_SHORT );
				t.setGravity( Gravity.CENTER, 0, 0 );
				t.show();
				
				this.volta();
	        } else
				mensagem = R.string.msgErroSalvar;
	        
	    } catch (IOException e) {
	    	mensagem = R.string.msgErroConectar;
	    }
		
	    return mensagem;
	}
}